import React, { useState, useEffect } from "react";
import apiClient from "../../utils/apiClient";
import "./index.css";

const KnowledgeBasePage = ({ kbId, kbName }) => {
  
  const [documents, setDocuments] = useState([]);
  const [searchTerm, setSearchTerm] = useState("");
  const [isLoading, setIsLoading] = useState(true);

  useEffect(() => {
    setIsLoading(true);
    // Fetching documents for the given kbId
    console.log(`Fetching documents for KB ID: ${kbId}, Name: ${kbName}`);
    
    // 使用正确的API路径
    apiClient
      .get(`/knowledge-bases/${kbId}/documents`)
      .then((response) => {
        if (Array.isArray(response.data)) {
          setDocuments(response.data);
        } else {
          console.warn("Unexpected response format:", response.data);
          setDocuments([]);
        }
        setIsLoading(false);
      })
      .catch((error) => {
        console.error("Failed to fetch documents:", error);
        setIsLoading(false);
      });
  }, [kbId, kbName]);

  const filteredDocs = documents.filter((doc) =>
    doc.title.toLowerCase().includes(searchTerm.toLowerCase())
  );

  const handleUploadDocument = () => {
    window.location.hash = `#/kb/${kbId}/upload`;
  };

  // Helper function to get correct document detail path
  const getDocumentDetailPath = (docId) => {
    return `#/kb/${kbId}/doc/${docId}`;
  }

  // Helper function to get correct edit path
  const getEditPath = (docId) => {
    return `#/kb/${kbId}/doc/${docId}/edit`;
  }

  if (isLoading) {
    return (
      <div className="container">
        <p className="loading-text">正在加载文档...</p>
      </div>
    );
  }

  return (
    <div className="container kb-page">
      <div className="page-header">
        <h1>{kbName || "AI 知识库"}</h1>
        <button onClick={handleUploadDocument}>
          <i className="fas fa-upload"></i> 上传文档
        </button>
      </div>

      <div className="kb-controls">
        <input
          type="search"
          placeholder="搜索文档..."
          value={searchTerm}
          onChange={(e) => setSearchTerm(e.target.value)}
          className="search-input"
        />
        <div className="doc-count">
          共 <span className="count-number">{filteredDocs.length}</span> 个文档
        </div>
      </div>

      {filteredDocs.length > 0 ? (
        <div className="compact-doc-list">
          <table className="doc-table">
            <thead>
              <tr>
                <th>文档名称</th>
                <th>类型</th>
                <th>更新时间</th>
                <th>状态</th>
                <th>操作</th>
              </tr>
            </thead>
            <tbody>
              {filteredDocs.map((doc) => (
                <tr key={doc.id} className="doc-row">
                  <td className="doc-title">
                    <a
                      href={getDocumentDetailPath(doc.id)}
                      onClick={(e) => {
                        e.preventDefault();
                        window.location.hash = getDocumentDetailPath(doc.id);
                      }}
                    >
                      {doc.title}
                    </a>
                  </td>
                  <td className="doc-type">{doc.type}</td>
                  <td className="doc-date">{doc.lastUpdated}</td>
                  <td className="doc-status">
                    <span className={`status-badge status-${doc.status}`}>
                      {doc.status}
                    </span>
                  </td>
                  <td className="doc-actions">
                    <button
                      className="action-btn view-btn small-btn"
                      title="查看"
                      onClick={() =>
                        (window.location.hash = getDocumentDetailPath(doc.id))
                      }
                    >
                      <i className="fas fa-eye"></i>
                    </button>
                    <button
                      className="action-btn edit-btn small-btn"
                      title="编辑"
                      onClick={() =>
                        (window.location.hash = getEditPath(doc.id))
                      }
                    >
                      <i className="fas fa-edit"></i>
                    </button>
                    <button
                      className="action-btn delete-btn small-btn"
                      title="删除"
                      onClick={() => {
                        if (
                          window.confirm(`确定要删除文档 "${doc.title}" 吗？`)
                        ) {
                          alert("删除功能模拟：文档已删除");
                          setDocuments((docs) =>
                            docs.filter((d) => d.id !== doc.id)
                          );
                        }
                      }}
                    >
                      <i className="fas fa-trash"></i>
                    </button>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      ) : (
        <p className="empty-state">
          此知识库中还没有文档。{" "}
          <a href={`#/kb/${kbId}/upload`}>上传第一个文档？</a>
        </p>
      )}
    </div>
  );
};

export default KnowledgeBasePage;
